package com.coolw.dynamic.thread.pool.context;

import org.dromara.hutool.core.map.MapUtil;
import org.slf4j.MDC;

import java.util.Map;
import java.util.concurrent.*;

/**
 * 动态线程池执行器
 *
 * @author coolw
 * @date 2024/5/21 16:38
 */
public class DynamicThreadPoolExecutor extends ThreadPoolExecutor {

    /**
     * 线程池名称
     */
    private String threadPoolName;

    public DynamicThreadPoolExecutor(String threadPoolName,
                                     int corePoolSize,
                                     int maximumPoolSize,
                                     long keepAliveTime,
                                     TimeUnit unit,
                                     BlockingQueue<Runnable> workQueue,
                                     ThreadFactory threadFactory,
                                     RejectedExecutionHandler handler) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
        this.threadPoolName = threadPoolName;
    }

    /**
     * 线程执行
     */
    @Override
    public void execute(Runnable runnable) {
        // 将父线程的MDC传递给子线程
        Map<String, String> contextMap = MDC.getCopyOfContextMap();
        if (MapUtil.isNotEmpty(contextMap)) {
            MDC.setContextMap(contextMap);
        }
        try {
            runnable.run();
        } finally {
            MDC.clear();
        }
    }
}
